package cn.wygandwdn.core.serializer.gson;

import cn.wygandwdn.common.enumeration.SerializerType;
import cn.wygandwdn.core.serializer.WtSerializer;
import com.google.gson.*;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/24 17:14
 */

public class GsonSerializer implements WtSerializer {


    @Override
    public <T> byte[] serializeToByte(T obj) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
        String json = gson.toJson(obj);
        return json.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public <T> T deserializeFromByte(byte[] data, Class<T> cls) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
        String json = new String(data);
        Object o = gson.fromJson(json, cls);
        return (T) o;
    }

    @Override
    public String getType() {
        return SerializerType.Gson.getType();
    }

    class ClassCodec implements com.google.gson.JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {

        @Override
        public Class<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            try {
                String str = json.getAsString();
                return Class.forName(str);
            } catch (ClassNotFoundException e) {
                throw new JsonParseException(e);
            }
        }

        @Override             //   String.class
        public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) {
            // class -> json
            return new JsonPrimitive(src.getName());
        }
    }
}
